package com.css.gdzj.gdzjbxgd.sys.user.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import com.css.aq.server.service.BaseService;
import com.css.gdzj.gdzjbxgd.common.annotation.SysLog;
import com.css.gdzj.gdzjbxgd.common.util.Constant;
import com.css.gdzj.gdzjbxgd.common.util.R;
import com.css.gdzj.gdzjbxgd.common.util.Restful.RestfulUtil;
import com.css.gdzj.gdzjbxgd.common.util.loginInfo.GetLoginInfo;
import com.css.gdzj.gdzjbxgd.common.validator.ValidatorUtils;
import com.css.gdzj.gdzjbxgd.modules.reportcontral.entity.BxgdReportContralEntity;
import com.css.gdzj.gdzjbxgd.modules.reportcontral.service.BxgdReportContralService;
import com.css.gdzj.gdzjbxgd.modules.userinfo.repository.entity.UserInfoEntity;
import com.css.gdzj.gdzjbxgd.modules.userinfo.service.UserInfoService;
import com.css.gdzj.gdzjbxgd.sys.user.entity.LoginUser;
import com.css.gdzj.gdzjbxgd.sys.user.entity.User;
import com.css.gdzj.gdzjbxgd.sys.user.form.LoginForm;
import com.css.gdzj.gdzjbxgd.sys.user.service.UserService;
import com.css.gdzj.gdzjbxgd.sys.user.service.impl.UserServiceImpl;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
/*import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;*/

import org.springframework.http.*;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 登录逻辑
 *
 * @author liangxg
 */
@RestController
@RequestMapping("/login")
@PropertySource(value = "classpath:base.properties")
public class LoginController {
    @Autowired
    UserServiceImpl userServiceImp;
    @Autowired
    HttpServletRequest request;
/*    @Autowired
    RestTemplate restTemplate;*/
    @Autowired
    private GetLoginInfo getLoginInfo;
    @Autowired
    private UserInfoService userInfoService;

    //HttpServletResponse response;

/*    @Autowired
    private RedisTemplate redisTemplate;*/
    @Value("${BASE_URL}")
    private String BASE_URL;
    @Value("${BASE_LOGIN_CONTROLLER}")
    private String BASE_LOGIN_CONTROLLER;
    @Autowired
    BaseService baseService;
    @Autowired
    private UserService userService;
    @Autowired
    private BxgdReportContralService bxgdReportContralService;

    /* @SysLog("用户登录base")*/
    @PostMapping("/doLogin")
    synchronized public R loginAP(@RequestBody LoginForm loginForm, HttpServletResponse response) throws IOException {

        // 若session中token不为空，则移除token
        HttpSession session = request.getSession();
        session.setMaxInactiveInterval(3600);
        //获取用户信息
        Map body = userInfoService.loginGetUserinfo(loginForm);
        UserInfoEntity userInfoEntity = new UserInfoEntity();
        userInfoEntity = (UserInfoEntity) body.get("data");
        if (userInfoEntity != null){
/*            if(StringUtils.isEmpty(userInfoEntity.getUserId())){
                return R.error("用户名或密码错误");
            }
*/
            if(Constant.DELETE.equals(userInfoEntity.getDelFlag())){
                return R.error("该用户已被停用");
            }
        }else {
            return R.error("账户不存在或密码错误");
        }

        String userId = userInfoEntity.getUserId();
        if (!StringUtils.isEmpty(userInfoEntity.getUserId())) {
            /*判断当前是否在登录时间内*/
            HashMap<String, Object> map = new HashMap<>();
            BxgdReportContralEntity  bxgdTimeDuring= bxgdReportContralService.selectLimitTime();
            if(bxgdTimeDuring==null){
                return R.error("填报时间未控制");
            }
                SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String reportTimeStart = bxgdTimeDuring.getReportTimeStart();
                String reportTimeEnd = bxgdTimeDuring.getReportTimeEnd();
                String reportYear = bxgdTimeDuring.getReportYear();
            boolean flag=false;
                try {
                    /*判断填报开关是否开启*/
                    String userReportFlag = userInfoEntity.getUserReportFlag();
                    Date start = sf.parse(reportTimeStart);
                    Date end = sf.parse(reportTimeEnd);
                    Date now = new Date();
                    flag=(now.getTime()>=start.getTime())&&(now.getTime()<=end.getTime())&&"1".equals(userReportFlag)?true:false;
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                map.put("flag",flag);
                map.put("start",reportTimeStart);
                map.put("end",reportTimeEnd);
                map.put("reportYear",reportYear);
            session.setAttribute("userId", userId);
            session.setAttribute("userName", loginForm.getLoginName());
            session.setAttribute("password", loginForm.getPassword());
            session.setAttribute("_USER_LOGIN_INFO_", userInfoEntity);
            return R.ok("登录成功").put("data", userInfoEntity).put("token","_USER_LOGIN_INFO_").put("timeMap",map);
        } else {
            return R.error("用户不存在或密码错误");
        }
    }

    /***
     * 登录验证
     * @param loginForm
     * @return
     */
    @SysLog("用户登录 withoutBase")
    @PostMapping("/checkUser")
    public R checkLogin(@RequestBody LoginForm loginForm) {
        try {
            //表单验证
            ValidatorUtils.validateEntity(loginForm);
            //获取登录用户名
            String userName = loginForm.getLoginName();
            //获取登录密码
            String password = DigestUtils.sha256Hex(loginForm.getPassword());
            User user = userServiceImp.findUserByNameAndPwd(userName, password);
            if (user == null || "".equals(user)) {
                return R.error(500, "用户不存在");
            } else {
                HttpSession session = request.getSession();
                session.setAttribute("userName", userName);
                Cookie cookie = new Cookie("userName", userName);
                cookie.setPath("/");
                //response.addCookie(cookie);
                return R.ok("登录成功！");
            }

        } catch (Exception e) {
            return R.error(e.getMessage());
        }
    }

    /**
     * 退出逻辑
     *
     * @param response
     * @return
     */
    @PostMapping("/logout")
    public R loginOut(HttpServletResponse response) {

        try {
            //获取session
            HttpSession session = request.getSession();
            String token = request.getHeader("token");
            UserInfoEntity userInfo = (UserInfoEntity) session.getAttribute(token);
            if(null==userInfo || StringUtils.isEmpty(userInfo)){
                return R.ok();
            }
            String userId = userInfo.getUserId();
            //移除session
            session.removeAttribute(token);
            return R.ok();
        }catch (Exception e){
            return R.error(e.getMessage());
        }
    }

}
